<template>
  <el-dialog
      v-model="visible"
      title="添加收货地址"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="handleClose"
      custom-class="address-dialog"
  >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="选择地址" required>
          <el-row :gutter="20">
            <el-col style="width: 200px" :span="8">
              <el-select
                  v-model="form.province"
                  placeholder="请选择省份"
                  @change="handleProvinceChange"
                  clearable
              >
                <el-option
                    v-for="item in provinces"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                />
              </el-select>
            </el-col>
            <el-col style="width: 200px" :span="8">
              <el-select
                  v-model="form.city"
                  placeholder="请选择城市"
                  @change="handleCityChange"
                  :disabled="!form.province"
                  clearable
              >
                <el-option
                    v-for="item in cities"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                />
              </el-select>
            </el-col>
            <el-col style="width: 200px" :span="8">
              <el-select
                  v-model="form.area"
                  placeholder="请选择区县"
                  :disabled="!form.city || areaDisabled.value"
                  clearable
              >
                <el-option
                    v-for="item in areas"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                />
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="详细地址" prop="detailAddress" required>
          <el-input
              v-model="form.detailAddress"
              placeholder="请输入街道门牌号信息"
              clearable
          />
        </el-form-item>

        <el-form-item label="手机号码" prop="telephone" required>
          <el-input
              v-model="form.telephone"
              placeholder="请输入11位手机号"
              clearable
              maxlength="11"
              show-word-limit
          />
        </el-form-item>

        <el-form-item label="收件人" prop="receiver" required>
          <el-input v-model="form.receiver" placeholder="请输入姓名" clearable />
        </el-form-item>

        <el-form-item label="默认地址">
          <el-switch v-model="form.isDefault" active-text="是" inactive-text="否" />
        </el-form-item>
      </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import {ref, reactive, onMounted, watch} from 'vue'
import { ElMessage } from 'element-plus'
import axios from "axios";
import { userStore } from '@/store/index.js'
const userItemStore = userStore();

//父传子
const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false,
    required:false
  }
})
watch(()=>props.dialogVisible,(newValue)=>{
  visible.value=newValue;
})
const visible = ref(false)
const emits = defineEmits("");
const handleClose = () => {
  visible.value = false
  emits("visible", visible.value)
}
watch(()=>props.dialogVisible,(newValue)=>{
  visible.value = newValue;
})


// 地址数据
const provinces = ref([])
const cities = ref([])
const areas = ref([])

// 表单数据
const form = ref({
  province: '',
  city: '',
  area: '',
  detailAddress: '',
  telephone: '',
  receiver: '',
  isDefault: false,
  status:"1",
  userId:null
})

// 表单验证规则
const rules = reactive({
  detailAddress: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ],
  telephone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  receiver: [
    { required: true, message: '请输入收件人姓名', trigger: 'blur' }
  ]
})

const formRef = ref(null)

const loading = ref(false)





// 提交表单
const handleSubmit = () => {
  if (!form.value.province || !form.value.city) {
    ElMessage.warning('请选择完整的省市区信息')
    return
  }

  form.value.isDefault=true?1:0;
  form.value.status="1";
  form.value.userId=userItemStore.user.id;
  formRef.value.validate(valid => {
    if (valid) {
      loading.value = true
      axios.post(`address/addAddress`, form.value).then(resp => {
        ElMessage.success(resp.data)
        //通知父组件刷新加载新地址
        emits("reloadAddress");
        handleClose();

      })

      // // 模拟API请求
      // setTimeout(() => {
      //   // 返回表单数据
      //   const addressData = {
      //     ...form,
      //     provinceName: getRegionName(form.value.province, provinces.value),
      //     cityName: getRegionName(form.value.city, cities.value),
      //     districtName: getRegionName(form.value.district, districts.value)
      //   }
      //
      //   console.log('提交的地址数据:', addressData)
      //   ElMessage.success('地址添加成功')
      //   handleClose()
      //   loading.value = false
      // }, 800)
    }
  })
}

// 获取区域名称
const getRegionName = (id, list) => {
  const item = list.find(item => item.id === id)
  return item ? item.name : ''
}

// 重置表单
const resetForm = () => {
  form.province = ''
  form.city = ''
  form.area = ''
  form.detailAddress = ''
  form.telephone = ''
  form.receiver = ''
  form.isDefault = false

  cities.value = []
  areas.value = []

  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 省份变更
const handleProvinceChange = () => {
  // 根据省份获取城市列表
  axios.get(`/china/getCities/${form.value.province}`).then(response => {
    cities.value = response.data
  }).catch(error => {
    ElMessage.error(error.response.data)
  })
}

// 城市变更
const areaDisabled=ref(false);
const handleCityChange = () => {
  // 根据城市获取区县列表
  axios.get(`/china/getDistricts/${form.value.city}`).then(response => {
    areas.value = response.data
    if (areas.value.length === 0) {
      areaDisabled.value = true;
      form.value.area = '';
    }else {
      areaDisabled.value = false;
    }
  }).catch(error => {
    ElMessage.error(error.response.data)
  })
}


const getProvinces = () => {
  axios.get(`/china/getProvinces`).then(resp => {
    provinces.value = resp.data
  })
}
// 初始化省份数据
onMounted(() => {
  getProvinces();
})

</script>

<style scoped>
.address-dialog .el-dialog__header {
  background-color: #ff7d00;
  color: white;
}

.address-dialog .el-dialog__title {
  color: white;
}

.address-dialog .el-button--primary {
  background-color: #ff7d00;
  border-color: #ff7d00;
}

.address-dialog .el-button--primary:hover {
  background-color: #ff9a3c;
  border-color: #ff9a3c;
}
</style>